Getting started with Python

In this book, we will be applying various analytical tools to different datasets in order to explore some of the strategic marketing issues widely encountered by practitioners. To this end, we will use the software called Python.

This section aims to prepare you for the upcoming data applications as there are a few things you should do and know before you can start using Python for marketing analytics. Specifically, you will learn how to:

  • install Python, Anaconda, and Jupyter Notebooks
  • install and load Python libraris
  • create a simple Jupyter notebook document
  • import (export) data to (from) Python.on### What is Python?

Python is a high-level programming language well-suited for a wide range of applications in data science, artificial intelligence, and web development, thanks to its extensive library and reputation for readability and adaptability. The package management in Python is facilitated by Anaconda, an efficient distribution platform that supports machine learning, data research, and scientific computing by bundling the necessary libraries. For working with Python, we generally use two different file formats:

  • Python script (.py)
  • Interactive Jupyter Notebook (.ipynb)

Throughout the book, we will work with .ipynb files since they are easy to interact with and give opportunities to integrate LaTeX and Python scripts in organized chunks. To work with .ipynb files, we need a text editor or an Integrated Development Environment (IDE). Here, we will introduce:

  • Spyder: IDE for Python with features tailored for scientific computing.
  • Jupyter Notebook: An open-source interactive computing tool that allows the creation and sharing of live code and visualizations
  • Google Colab: A cloud-based platform for running Python code collaboratively.

y.

.

1. Installing Python and Anaconda¶

To install Python, go to https://www.anaconda.com/download, and download the latest version of Anaconda with the latest version of Python. You can choose a different installer depending on the operating system of your computer.

Anaconda_1.png

If you encounter any problems, you can always consult on the installation documentation https://docs.anaconda.com/free/anaconda/install/index.html .

2. Installing the JupyterLab¶

Assuming that we have successfully installed Anaconda, we have also automatically installed Jupyter Notebook. However, for our purposes, Jupyter Notebook alone is insufficient as we will need a variable explorer. We need to install JupyterLab now.

Go to https://jupyter.org/install to read the installation guide. Using the start button on Windows, open the Anaconda Prompt. You will see the following window:

Anaconda_prompt.png

For MAC, it is not required to run Anaconda Prompt. MAC users can directly open the terminal and follow the steps below.

To install the JupyterLab, type the following in the terminal and press the Enter key on your keyboard:

pip install jupyterlab

installing_JupyterLab.png

The last step is to integrate a variable inpsector to the JupyterLab that can be found in the following github link:

https://github.com/jupyterlab-contrib/jupyterlab-variableInspector.

Run the following command in the Anaconda terminal:

pip install lckr_jupyterlab_variableinspector

variable_inspector1.png

Now, you can open the Anaconda Navigator and launch the JupyterLab to write/edit your codes, as shown in the following images.

anaconda_navigator1.png

anaconda_navigator2.png

Note that with the installation of the plug-in, JupyterLab becomes the most powerful and user-friendly tool we have. However, it is still possible to use Jupyter Notebook. Lastly, while we can use Google Colab, it requires an internet connection and can be a bit tricky to work with local data files. Therefore, it is not recommended for beginners.

Whenever you need to open JupyterLab, open the Anaconda Navigator and click on the launch button as we did before. The image below shows different functionalities of JupyterLab.

jupyterlab_functionalities.png

After we open a new file, we can start typing our code in the chunks/cells as shown in the image below.

typing_python_code.png

The following code illustrates how the variable inspector works in Python.

In [21]:
# This is a sample code to show the variable inspector

import numpy as np
array1 = np.ones((3,10))

list1 = ['1', '10', '23', '21', '5']

int1 = 42

string1 = 'This is the Python installation tutorial'

do_you_like_python = True

We run the Python code above by clicking the 'Run' button located at the top of the screen:

run_button.png

Next, by right-clicking with our mouse, we can open the variable inspector and view the variables in detail in a new window. See the images below.

variable_inspector2_1.png

variable_inspector2_2.png

For some cells, if we want to add comments when typing Python codes, we can do so by adding a hashtag '#' before the comment in a code cell, as shown in the code chunk above.

If we want to add a long comment, such as a task description, we can enclose the text within triple quotes ('''). This allows us to include a paragraph with new lines, as shown below.

In [22]:
'''
    This is a sample comment cell.
    You can write anything inside it.
    You don't need to bother with hashtags
    with each newline.
'''

print('Done')
Done

Let's assume that we want to view the values inside a variable on the console by printing it. Can we do this without the variable inspector? Where can we plot the values? When using the .ipynb format, all console outputs are directly shown under the cells, as in the example below.

In [3]:
import matplotlib.pyplot as plt

x = np.arange(1,8)
y = x**2

plt.plot(x,y)
plt.title('x^2 Plot for Integers between 1-7')
plt.xlabel('x')
plt.ylabel('y')
Out[3]:
Text(0, 0.5, 'y')
No description has been provided for this image

After working with our file, we should save it using the disk icon on the left corner of the screen, as we explored before. We can save and export this file in various formats, including PDF, HTML, LaTeX, Markdown, and so on. To do this, we need to click on ‘File’>’Save and Export Notebook As…’, as shown in the image below.

saving_notebook_file.png

Additionally, we can select 'Save Notebook As' to change the file’s directory and name, as shown in the image below.

changing_notebook_file_name.png

Lastly, we can specify our directory or create a new folder by clicking on the folder icon in the left window, browsing to our desired location, and clicking on the ‘new folder’ icon, represented by a folder with a plus sign. See the image below.

changing_working_directory.png

Additionally, we can create our working directory in our computer or Mac’s file explorer and specify it using this browsing method to open our file.

Suppose we want to work in the 'Downloads' directory. We can create a file named 'marketing_analytics' (or any name you prefer), as we have done previously, and then create new .ipynb files to work on them.

Importing data to Python¶

Companies monitor a wide range of internal data, including both online and offline sales, advertising expenditures, website visitors, click counts, and click-through rates (CTR), among others. In this book, using Python, we will develop models that leverage these datasets. It is essential, therefore, to understand how to import and export this data effectively. Since data can be stored in various formats, we will concentrate on the most commonly used ones: Excel files and CSV files. We typically work with Excel (.xlsx) or Comma Separated Values (.csv) file types. The recommended approach to read these files is by using libraries like numpy or pandas. If we have not previously installed a library, it is typical for us to encounter errors like the one shown below.

library_installation_errors.png

To avoid such issues, we can include a code snippet like the one below, which attempts to install any missing libraries during the execution of the code.

In [24]:
import subprocess
import sys

libraries_to_install = ['emoji', 'numpy', 'pandas', 'torch']

try:
    for library in libraries_to_install:
        __import__(library)
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install"] + libraries_to_install)
finally:
    for library in libraries_to_install:
        globals()[library] = __import__(library)

If a library is not present in our Anaconda environment, the code will automatically install it upon an import attempt. Once the installation is successful, the libraries will be imported and ready for use.

Importing an Excel file¶

Now that we have our libraries ready, we can use them to import data files. The data file you will import is named ‘fourtex_data_example’ and can be found in the provided folder. To proceed, insert the following command into the code cell you created earlier.

In [25]:
data = pandas.read_excel("C:/Users/gyildiri/Downloads/chapter 1/fourtex_data_example.xlsx")
data.head()
Out[25]:
week_beg Google_Adwords Facebook TV Radio traffic
0 2020-07-06 94017.2 82950 0.0 0.0 6719812
1 2020-07-13 93634.5 66150 0.0 0.0 6186229
2 2020-07-20 112239.4 94650 0.0 0.0 6790416
3 2020-07-27 121250.3 96450 0.0 0.0 7146957
4 2020-08-03 130470.9 114600 0.0 0.0 7815741

Ensure that the data file is located in the same directory as your .ipynb file. The command data.head()in the code allows us to examine the first few rows of the dataset.

Importing CSV data¶

CSV stands for Comma Separated Values. Essentially, CSV files are simple text files that can be opened with programs like Notepad or Excel. To import a CSV data file, simply add a new code chunk to your Jupyter Notebook and type the following command within the cell:

In [26]:
data_csv = pandas.read_csv("C:/Users/gyildiri/Downloads/chapter 1/data1.csv")

data_csv.head()
Out[26]:
Date Sales
0 2012-01 4715.0
1 2012-02 4386.0
2 2012-03 4408.0
3 2012-04 4477.0
4 2012-05 4998.0

The command data_csv.head() in the code helps us examine the first few rows of the dataset.

Exporting data from Python¶

Suppose you have completed your Python session and now have data you wish to use elsewhere. You might want to export this data to other formats like Excel or CSV. Perhaps you aim to enhance your plots in Excel using the data generated in Python, or maybe you need to continue your work in another software and require the data in a CSV file. Python allows you to do both. Let us begin by exploring how to export Python data to an Excel file.

From Python to Excel¶

We can use the Pandas and NumPy libraries to export our data to a specified directory. Let's say we want to export the 'data_excel' into an Excel file located in the working directory and name it 'output'. The following Python code shows an example of exporting a data file named ‘data_excel’ into an Excel file, output.xlsx, located in the working directory.

In [27]:
data_excel = numpy.arange(1,100)

# Specify the Excel file path
excel_file_path = "C:/Users/gyildiri/Downloads/chapter 1/output.xlsx"

# Create a Pandas DataFrame from the NumPy array
df = pandas.DataFrame(data_excel)

# Write the DataFrame to an Excel file
df.to_excel(excel_file_path, index=False, header=False) # You can adjust options based on your needs

print(f'Data has been exported to {excel_file_path}')
Data has been exported to C:/Users/gyildiri/Downloads/chapter 1/output.xlsx

Note that we have converted the NumPy array into a pandas dataframe to take full advantage of the extensive capabilities of the pandas library.

From Python to CSV¶

To export your Python data to a CSV file, type the following command in your code cell in JupyterLab and execute it. Please ensure you include the directory and filename in the first input, as shown in the code snippet below. Then, specify the Python data file you wish to export and choose a delimiter. For this implementation, you can use a comma (',') as the delimiter.

In [28]:
numpy.savetxt('C:/Users/gyildiri/Downloads/chapter 1/output_comma.csv', data_excel, delimiter=',')

Once you execute the above code, in your working directory you will see a CSV file called ‘output_comma’. So, you exported your Python numpy array to a CSV file.

Google Colab¶

We can use Google Colab to interact with existing .ipynb files or create one from scratch. After opening the website (https://colab.research.google.com/), you will see a window like the one shown.

launching_colab_file.png

To start a new interactive Jupyter notebook, simply click on the 'New Notebook' button. If you wish to edit your existing files, you can click on the 'Upload Notebook' button as well.

In essence, the interface is similar to what we have in JupyterLab, you can add code or text cells or chunks according to your needs.

google_colab_file.png

You can share your files for collaborative work similar to Google Docs and access them via your Google Drive. Additionally, if you opt for premium features, you can run your codes overnight for more complex machine learning tasks. However, since we aren't dealing with such advanced material here, Google Colab primarily serves as a useful tool for backing up your files and continuing your work on any computer or tablet with internet access. This means that if you encounter any issues with your PCs or Macs, or if you forget to bring your laptop, you can still use Colab on your tablet.

Moreover, Colab also includes a variable inspector. This feature allows you to inspect your variables directly in Google Colab file, as shown in the image below.

variable_inspector_google_colab.png

These are all the important steps in getting Python up and running. You are now ready to analyse your first dataset in the next chapter.

Additional resources¶

In the middle of exploring the intricate world of programming, you may find yourself exclaiming in bewilderment, “Oh my goodness! What precisely does this code accomplish? How am I to craft such code endowed with this functionality?” Such queries, undoubtedly, will surface in the depths of your mind throughout this learning journey. In today’s world, advanced language models like ChatGPT by OpenAI (https://chat.openai.com/) can be a great help. They allow users to understand, improve, and debug code more efficiently, freeing users from constant typing. This gives users more time to focus on designing the architecture itself.

If you prefer sticking to more traditional, forum-like sites, Stack Overflow (https://stackoverflow.com/) is a reliable choice.

In addition, it is always wise to consult the official documentation for Python and its libraries:

  • https://docs.python.org/3
  • https://pandas.pydata.org/docs

Finally, the following cheat sheets for commonly used Python libraries are helpful resources.

  • https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf
  • https://www.datacamp.com/cheat-sheet/numpy-cheat-sheet-data-analysis-in-python
In [ ]: